package org.abac4j.aspect;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import org.abac4j.context.AbacContext;
import org.abac4j.evaluation.AbacELAnnotationEvaluator;
import org.abac4j.evaluation.AbacEvalutatorService;

public class SecurityCGLIBProxy implements MethodInterceptor, SecurityInterceptor {
	private Object obj;
	private AbacContext context;
	
	private SecurityCGLIBProxy(Object obj, AbacContext context){
		this.context = context;
		this.obj = obj;
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		return intercept(obj, method, args);
	}
	
	@SuppressWarnings("unchecked")
	public static <E> E createSecurityInterceptor(E obj, AbacContext context){
		SecurityCGLIBProxy proxy = new SecurityCGLIBProxy(obj, context);
		Enhancer e = new Enhancer();
		e.setSuperclass(obj.getClass());
		e.setCallback(proxy);
		return (E) e.create();
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args) throws Exception {
		AbacEvalutatorService evaluator = new AbacELAnnotationEvaluator();
		return evaluator.evaluate(context, this.obj, method, args);
	}
}
